<?php
/**
 * 作者: 王志昂-黑米<wangzhiangtony@qq.com>
 * 个人说明: 春水初涨，春林初盛，春风十里，不如你。
 * 创建时间: 2016-01-21 21:28
 * 说明:
 */

namespace Home\Controller;

use Think\Controller;
use Think\Log;

class CodeController extends CommonAction
{

    public function CodeController()
    {
        parent::__construct();
    }

    protected function _getNavigator($name, $action)
    {
        $navigator = array(
            array(
                'name' => '代码审查',
                'url'  => '###'
            ),
            array(
                'name' => $name,
                'url'  => $action
            )
        );
        return $navigator;
    }

    public function manage_git()
    {
        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator('Git管理', '/home/' . $sectionId));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function subscribe()
    {
        $sectionId = $this->_getSectionId(__CLASS__, __FUNCTION__);
        $this->assign('navigator', $this->_getNavigator('订阅代码', '/home/' . $sectionId));
        $this->assign('section', $sectionId);
        $this->display();
    }

    public function save_git_project()
    {
        $id          = $this->_getParam("id", null);
        $projectName = $this->_getParam("projectName");
        $gitUrl      = $this->_getParam("gitUrl");
        $userId      = $_SESSION['user_id'];
        $now         = date("c");
        $data        = array(
            "gmt_modified" => $now,
            "modifier"     => $userId,
            "project_name" => $projectName,
            "git_url"      => $gitUrl
        );
        if (empty($id)) {
            $data['creator']    = $userId;
            $data['gmt_create'] = $now;
            $res                = M("CodeGitProject")->add($data);
        } else {
            $res = M("CodeGitProject")->where("id=" . $id)->save($data);
        }
        if ($res > 0) {
            $ret = array(
                'errorCode' => '0',
                'errorMsg'  => '保存成功！'
            );
        } else {
            $ret = array(
                'errorCode' => '-1',
                'errorMsg'  => '保存失败！'
            );
        }
        $this->ajaxReturn($ret);
    }

    public function get_git_project_list()
    {
        $id          = $this->_getParam("id", null);
        $projectName = $this->_getParam("projectName");
        $gitUrl      = $this->_getParam("gitUrl");
        $page        = $this->_getParam("page", 1);
        $pageSize    = $this->_getParam("pageSize", 15);

        if (empty($page)) {
            $page = 1;
        }
        $condition = array();
        if ( ! empty($id)) {
            $condition['id'] = $id;
        }
        if ( ! empty($projectName)) {
            $condition['project_name'] = $projectName;
        }
        if ( ! empty($gitUrl)) {
            $condition['git_url'] = $gitUrl;
        }
        $res = M("CodeGitProject")->where($condition)->order('id DESC')->select();
        $count = sizeof($res);

        if (!empty($pageSize)) {
            $offset = ($page - 1) * $pageSize;
            $res = array_slice($res, $offset, $pageSize);
        }
        $currentProjectArr = $this->_getCurrentGitProject();
        foreach ($res as $key => $item) {
            if (in_array($item['git_url'], $currentProjectArr)) {
                $res[$key]['hasPull'] = true;
            } else {
                $res[$key]['hasPull'] = false;
            }
        }
        if ($page == 1) {
            $first     = true;
            $firstPage = true;
        } else {
            $first     = false;
            $firstPage = false;
        }
        if ($page == $count) {
            $last     = true;
            $lastPage = true;
        } else {
            $last     = false;
            $lastPage = false;
        }
        $totalPages = ceil($count / $pageSize);
        $number     = $page - 1;
        $ret        = array(
            'errorCode' => '0',
            'errorMsg'  => 'success',
            'data'      => array(
                'content'          => $res,
                'totalElements'    => $count,
                'first'            => $first,
                'firstPage'        => $firstPage,
                'last'             => $last,
                'lastPage'         => $lastPage,
                'number'           => $number,
                'numberOfElements' => $pageSize,
                'size'             => $pageSize,
                'totalPages'       => $totalPages
            )
        );
        $this->ajaxReturn($ret);
    }

    private function _getCurrentGitProject()
    {
        exec("(cd Git;ls)", $directories);
        $projectArr = array();
        foreach ($directories as $directory) {
            $urls = array();
            exec("(cd Git/" . $directory . ";git remote -v)", $urls);
            $urlStr       = $urls[0];
            $urlArr       = explode('	', $urlStr);
            $urlArr2      = explode(' ', $urlArr[1]);
            $url          = trim($urlArr2[0]);
            $projectArr[] = $url;
        }
        return $projectArr;
    }

    public function get_subscribe_git_project_list()
    {
        $projectName = $this->_getParam("projectName");
        $gitUrl      = $this->_getParam("gitUrl");
        $page        = $this->_getParam("page", 1);
        $pageSize    = $this->_getParam("pageSize", null);
        $userId      = $_SESSION['user_id'];
        $offset      = ($page - 1) * $pageSize;

        $sql   = "SELECT
                b.project_name,
                b.git_url,
                group_concat(c.realname) as users,
                group_concat(c.id) as userIds
            FROM
                zt_code_subscribe_git AS a
            LEFT JOIN zt_code_git_project AS b ON a.git_project_id = b.id
            LEFT JOIN zt_user AS c ON a.user_id_subscribe_to = c.id
            WHERE
                a.user_id_subscriber = " . $userId . "
            AND a.is_deleted = 'N'
            GROUP BY
                a.git_project_id
            LIMIT " . $offset . ", " . $pageSize;
        $res   = M()->query($sql);
        $count = sizeof($res);
        if ($page == 1) {
            $first     = true;
            $firstPage = true;
        } else {
            $first     = false;
            $firstPage = false;
        }
        if ($page == $count) {
            $last     = true;
            $lastPage = true;
        } else {
            $last     = false;
            $lastPage = false;
        }
        $totalPages = ceil($count / $pageSize);
        $number     = $page - 1;
        $ret        = array(
            'errorCode' => '0',
            'errorMsg'  => 'success',
            'data'      => array(
                'content'          => $res,
                'totalElements'    => $count,
                'first'            => $first,
                'firstPage'        => $firstPage,
                'last'             => $last,
                'lastPage'         => $lastPage,
                'number'           => $number,
                'numberOfElements' => $pageSize,
                'size'             => $pageSize,
                'totalPages'       => $totalPages
            )
        );
        $this->ajaxReturn($ret);
    }

    public function save_subscribe_git_project()
    {
        $projectId = $this->_getParam("projectId", null);
        $userIds   = $this->_getParam("userIds", array());
        $userId    = $_SESSION['user_id'];

        $data             = array(
            'gmt_modified'       => date('c'),
            'modifier'           => $userId,
            'git_project_id'     => $projectId,
            'user_id_subscriber' => $userId
        );
        $result           = M('CodeSubscribeGit')->where('user_id_subscriber=' . $userId . ' and git_project_id=' . $projectId)->select();
        $currentSubscribe = array();
        foreach ($result as $value) {
            $currentSubscribe[] = $value['user_id_subscribe_to'];
        }
        $needDeleteUserArr = array_diff($currentSubscribe, $userIds);
        $needInsertUserArr = array_diff($userIds, $currentSubscribe);
        $needUpdateUserArr = array_intersect($userIds, $currentSubscribe);
        foreach ($needDeleteUserArr as $needDeleteUser) {
            $data['is_deleted'] = 'Y';
            M('CodeSubscribeGit')->where('user_id_subscriber=' . $userId . ' and user_id_subscribe_to=' . $needDeleteUser . ' and git_project_id=' . $projectId)->save($data);
        }

        foreach ($needInsertUserArr as $needInsertUser) {
            $data['is_deleted']           = 'N';
            $data['user_id_subscribe_to'] = $needInsertUser;
            $data['creator']              = $userId;
            $data['gmt_create']           = date('c');
            M('CodeSubscribeGit')->add($data);
        }

        foreach ($needUpdateUserArr as $needUpdateUser) {
            $data['is_deleted']           = 'N';
            $data['user_id_subscribe_to'] = $needUpdateUser;
            M('CodeSubscribeGit')->where('user_id_subscriber=' . $userId . ' and user_id_subscribe_to=' . $needUpdateUser . ' and git_project_id=' . $projectId)->save($data);
        }

        $ret = array(
            'errorCode' => '0',
            'errorMsg'  => '保存成功！'
        );
        $this->ajaxReturn($ret);
    }
}